package org.example.library.controller;

import org.example.library.pojo.BorrowRecord;
import org.example.library.pojo.dto.BorrowRecordDto;
import org.example.library.service.IBorrowRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/borrow-records") // RESTful API 路径前缀
public class BorrowRecordController {

    @Autowired
    private IBorrowRecordService borrowRecordService;

    /**
     * 添加借阅记录
     */
    @PostMapping
    public ResponseEntity<BorrowRecord> add(@Validated @RequestBody BorrowRecordDto borrowRecordDto) {
        BorrowRecord record = borrowRecordService.add(borrowRecordDto);
        return ResponseEntity.status(HttpStatus.CREATED).body(record); // 返回 201 Created 状态码
    }

    /**
     * 更新借阅记录
     */
    @PutMapping("/{recordId}")
    public ResponseEntity<BorrowRecord> update(
            @PathVariable Integer recordId,
            @Validated @RequestBody BorrowRecordDto borrowRecordDto) {
        borrowRecordDto.setId(recordId); // 设置 DTO 中的 ID
        BorrowRecord updatedRecord = borrowRecordService.update(borrowRecordDto);
        return ResponseEntity.ok(updatedRecord); // 返回更新后的记录
    }

    /**
     * 删除借阅记录
     */
    @DeleteMapping("/{recordId}")
    public ResponseEntity<Void> delete(@PathVariable Integer recordId) {
        borrowRecordService.delete(recordId);
        return ResponseEntity.noContent().build(); // 返回 204 No Content 状态码
    }

    /**
     * 根据 ID 查询借阅记录
     */
    @GetMapping("/{recordId}")
    public ResponseEntity<BorrowRecord> getRecordById(@PathVariable Integer recordId) {
        BorrowRecord record = borrowRecordService.getRecordById(recordId);
        return ResponseEntity.ok(record); // 返回查询到的记录
    }

    /**
     * 查询所有借阅记录（可选功能）
     */
    @GetMapping
    public ResponseEntity<List<BorrowRecord>> getAllRecords() {
        List<BorrowRecord> records = borrowRecordService.getAllRecords();
        return ResponseEntity.ok(records); // 返回所有借阅记录
    }
    /**
     * 还书操作
     */
    @PostMapping("/{recordId}/return")
    public ResponseEntity<BorrowRecord> returnBook(@PathVariable Integer recordId) {
        BorrowRecord updatedRecord = borrowRecordService.returnBook(recordId);
        return ResponseEntity.ok(updatedRecord); // 返回更新后的借阅记录
    }
}
